package com.keli.dt.model.bpss;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;

import com.keli.dt.model.RoadReport;

public class RoadReportInsertBPSS implements BatchPreparedStatementSetter {
	private List<RoadReport> roadReports;
	private String reportTime;

	public RoadReportInsertBPSS(List<RoadReport> roadReports, String reportTime) {
		this.roadReports = roadReports;
		this.reportTime = reportTime;
	}
	
	private static String insertSql(String tableName, String seq) {
		StringBuffer sql = new StringBuffer();
		sql.append("INSERT INTO ");
		sql.append(tableName);
		sql.append("(ID, DETECT_CLASS, ROAD_ID, VOLUME_NONMOTOR, FLOW_NONMOTOR, ");
		sql.append("VOLUME_MOTOR, FLOW_MOTOR, SPEED, CYCLE, REPORT_TIME, ");
		sql.append("DENSITY, COLLEC_TIME, COLLEC_DATETIME, SPEED_ANA, TPI, STATUS) VALUES(");
		sql.append(seq);
		sql.append(", ?, ?, ?, ?, ?, ?, ?, ?, TO_DATE(?, 'YYYY/MM/DD HH24:MI:SS'), ");
		sql.append(" ?, ?, TO_DATE(?, 'YYYY/MM/DD HH24:MI:SS'), ?, ?, ?)");
		
		return sql.toString();
	}
	
	public static String insertHistorySql() {
		return insertSql("DT_ROAD_REPORT_H", "ROAD_H_SEQ.NEXTVAL");
	}
	
	public static String insertRealTimeSql() {
		return insertSql("DT_ROAD_REPORT_R", "ROAD_R_SEQ.NEXTVAL");
	}

	@Override
	public void setValues(PreparedStatement ps, int i) throws SQLException {
		RoadReport rr = roadReports.get(i);
		int j = 1;		
		ps.setString(j++, rr.getDETECT_CLASS());
		ps.setBigDecimal(j++, rr.getROAD_ID());
		ps.setBigDecimal(j++, rr.getVOLUME_NONMOTOR());
		ps.setBigDecimal(j++, rr.getFLOW_NONMOTOR());
		ps.setBigDecimal(j++, rr.getVOLUME_MOTOR());
		ps.setBigDecimal(j++, rr.getFLOW_MOTOR());
		ps.setBigDecimal(j++, rr.getSPEED());
		ps.setBigDecimal(j++, rr.getCYCLE());
		ps.setString(j++, reportTime);
		ps.setString(j++, rr.getDENSITY());
		ps.setString(j++, rr.getCOLLEC_TIME());
		ps.setString(j++, rr.getCOLLEC_DATETIME());
		ps.setBigDecimal(j++, rr.getSPEED_ANA());		
		ps.setString(j++, formatTPI(rr.getTPI()));
		ps.setString(j++, rr.getSTATUS());
	}

	@Override
	public int getBatchSize() {
		return roadReports.size();
	}

	private String formatTPI(BigDecimal tpi) {
		String tpiString = tpi.toString();
		if (tpiString.length() > 10) {
			tpiString = tpiString.substring(0, 10);
		}
		return tpiString;
	}
}
